#include "mysqlManager.h"
#include "../log/log4z.h"

using namespace std;

SqlManager::SqlManager() : sqlConn(mysql_init(NULL))
{
    connectMysql();
}

SqlManager::~SqlManager()
{    
    mysql_close(sqlConn);
}

void SqlManager::connectMysql()
{
    mysql_real_connect(sqlConn, "127.0.0.1", "li", "123456", "tallyBook", 3306, NULL, CLIENT_MULTI_STATEMENTS);
}

SqlManager* SqlManager::self = nullptr;
mutex SqlManager::selfMutex;
SqlManager* SqlManager::getInstance()
{
    if(self == nullptr) {
        selfMutex.lock();
        if(self == nullptr) {
            self = new SqlManager();
        }
        selfMutex.unlock();
    }

    return self;
}

/**
 * 1. SQL 语句存在问题，字符串类型需要使用单引号或者双引号
 * 2. mysql_errno, mysql_error 获取错误和错误信息
 * 
 * 单引号在字符串中可以直接使用
 * 双引号需要加转义字符 \"
*/
bool SqlManager::isUserExist(const std::string &user)
{
    string sql = "select * from user where name = '" + user + "';";
    auto search_res = mysql_query(sqlConn, sql.c_str());
    if(mysql_errno(sqlConn) != 0) {
        LOGFMTE("[MySQL] %s, sql: %s", mysql_error(sqlConn), sql.c_str());
        return false;
    }
    auto result = mysql_store_result(sqlConn);
    int row = mysql_num_rows(result);//获取行数
    return row > 0 ? true : false;
}